import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
    login,
    loginCode,
    getInfo,
    getbumph_type,
    whoRead,
    getRouters
} from '@/api/http'
import {
    getToken,
    setToken,
    removeToken
} from '@/utils/auth'
const gwMenus = ['收文流转', '收文阅办', '阅办代理', '公文接收', '通知接收']
const baseUrl = config.baseUrl

const user = {
    state: {
        token: getToken(),
        name: storage.get(constant.name),
        avatar: storage.get(constant.avatar),
        roles: storage.get(constant.roles),
        permissions: storage.get(constant.permissions),
        departType: storage.get(constant.departType),
        bumph_type: uni.getStorageSync('bumph_type'),
        who_read: uni.getStorageSync('who_read'),
        user: storage.get(constant.user),
        menusPath: uni.getStorageSync('menusPath'),
        menusTabs: uni.getStorageSync('menusTabs') || []

    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_MENUS: (state, menusPath) => {
            state.menusPath = menusPath
            uni.setStorageSync('menusPath', menusPath)
    
            let arr =[
                  { name: "收文流转", id: 0 },
                  { name: "收文阅办", id: 1 },
                  { name: "阅办代理", id: 2 },
                  { name: "公文接收", id: 3 },
                  { name: "通知接收", id: 4 },
                ]
            state.menusTabs = arr
            uni.setStorageSync('menusTabs', arr)
            // const menusTabs = getMenusList(menusPath);
            // if (menusTabs) {
            //     state.menusTabs = menusTabs
            //     uni.setStorageSync('menusTabs', menusTabs)
            // }
        },
        SET_NAME: (state, name) => {
            state.name = name
            storage.set(constant.name, name)
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
            storage.set(constant.avatar, avatar)
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
            storage.set(constant.roles, roles)
        },
        SET_PERMISSIONS: (state, permissions) => {
            // console.log(permissions, 'permissionsss');

            state.permissions = permissions
            storage.set(constant.permissions, permissions)
        },
        SET_USER: (state, user) => {
            state.user = user
            storage.set(constant.user, user)

        },
        SET_DEPARTTYPE: (state, departType) => {
            state.departType = departType
            storage.set(constant.departType, departType)

        },
    },
    actions: {
        // 密码登录
        Login({
            commit
        }, userInfo) {
            const username = userInfo.username
            const password = userInfo.password
            const uuid = userInfo.uuid
            return new Promise((resolve, reject) => {
                login(username, password, uuid).then((res) => {
                    setToken(res.data.access_token)
                    commit('SET_TOKEN', res.data.access_token)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 验证码登录
        codeLogin({
            commit
        }, userInfo) {
            return new Promise((resolve, reject) => {
                loginCode(userInfo).then((res) => {
                    setToken(res.data.access_token)
                    commit('SET_TOKEN', res.data.access_token)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetInfo({
            commit,
            state
        }) {
            return new Promise((resolve, reject) => {
                getInfo().then((res) => {
                    const {
                        permissions,
                        roles,
                        user
                    } = res.data
                    const avatar = (user == null || user.avatar == "" || user.avatar == null) ? "@/static/images/profile.jpg" : baseUrl + user.avatar
                    const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.loginName
                    commit('SET_ROLES', roles)
                    commit('SET_PERMISSIONS', permissions)
                    commit('SET_DEPARTTYPE', user.org.departType)
                    commit('SET_NAME', username)
                    commit('SET_NAME', username)
                    commit('SET_USER', user)
                    // 获取一下下拉数据 存储于全局中
                    getbumph_type().then(res => {
                        uni.setStorageSync('bumph_type', res.data)
                    })
                    whoRead().then(res => {
                        uni.setStorageSync('who_read', res.data)
                    })
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取路由数据
        getMenus({
            commit,
            state
        }) {
            return new Promise((resolve, reject) => {
                getRouters().then((res) => {
                    commit('SET_MENUS', res.data)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 退出系统
        LogOut({
            commit,
            state
        }) {
            return new Promise((resolve, reject) => {
                logout().then((res) => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken()
                    storage.clean()
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        }
    }
}

const getMenusList = (menus) => {
    const documentArr = menus.find(v => {
        return v.path === '/document'
    })
    if (documentArr) {
        const matchedMenus = findMatches([documentArr], gwMenus);
        return matchedMenus.map((v, i) => {
            const idx = gwMenus.findIndex(ev => ev === v.meta.title)
            return {
                name: v.meta.title,
                id: idx
            }
        })
    }

}

function findMatches(arr1, arr2) {
    const matches = [];

    function recursiveSearch(arr) {
        for (let i = 0; i < arr.length; i++) {
            const item = arr[i];
            if (item.meta && item.meta.title && arr2.includes(item.meta.title)) {
                matches.push(item);
            }
            if (item.children && item.children.length > 0) {
                recursiveSearch(item.children);
            }
        }
    }
    recursiveSearch(arr1);
    return matches;
}
export default user